package org.flywaydb.core.internal.util;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author weixiaochun
 * @date 2024/1/3
 */
public class SQLFileParser {

    private static final Pattern PATTERN = Pattern.compile("--\\s*(\\w+):\\s*(.*)");

    private static final int MAX_COMMENT_LINE_COUNT = 3;

    public static Map<String, String> parserComment(String filePath){
        Map<String, String> paramMap = new HashMap<>(3);
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            int lineCount = 0;


            while ((line = br.readLine()) != null && lineCount < MAX_COMMENT_LINE_COUNT) {
                Matcher matcher = PATTERN.matcher(line);
                if (matcher.matches()) {
                    String parameter = matcher.group(1);
                    String value = matcher.group(2);
                    paramMap.put(parameter, value);
                }

                lineCount++;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return paramMap;
    }
}
